import {Component, OnDestroy, OnInit} from '@angular/core';
import {BasePage} from '../../common/basePage';
import {Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {HttpService} from '../../services/http.service';
import {LoanUploadItemsComponent} from '../../components/loan-upload-items/loan-upload-items.component';
import {AppConfig} from '../../common/app-config.enum';
import {ConfigService} from '../../services/config.service';

@Component({
  selector: 'app-loan-upload',
  templateUrl: './loan-upload.page.html',
  styleUrls: ['./loan-upload.page.scss'],
})
export class LoanUploadPage extends BasePage implements OnInit, OnDestroy {

  public dataList: any[] = [];

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              public configService: ConfigService,
              private modalCtrl: ModalController,
              private events: Events,
              private service$: HttpService
  ) {
    super(navCtrl, toastCtrl);
    // 侦听数据变化
    events.subscribe(AppConfig.TOPIC_USER_ITEMS, () => {
      this.getData();
    });
  }

  ngOnInit() {
    // 获取审核项目列表和相关附件列表
    this.getData();
  }

  ngOnDestroy() {
    this.events.unsubscribe(AppConfig.TOPIC_USER_ITEMS);
  }

  private getData() {
    this.service$.doRequest(UrlAndOPT.loan_upload)
      .subscribe(obj => {
        if (obj) {
          let items = [];
          this.dataList = obj['obj']['tasb'].map(data => {
            // 获取对应科目下的附件列表
            items = obj['obj']['userItems']
              .filter(item => item['bid_audit_subject_id'] === data['id'])
              .map(it => ({...it, url: this.HOST + it['url']}));
            // 默认科目状态无附件
            let status = 'NULL';
            if (items.length > 0) {
              let statusArr = items.map(it => it['status']);
              statusArr = Array.from(new Set(statusArr));
              // 优先级由高到低：未通过、未提交、待审核、已通过
              for (const s of ['PASS', 'WAIT_AUDIT', 'NO_SUBMIT', 'NO_PASS']) {
                if (statusArr.indexOf(s) > -1) {
                  status = s;
                }
              }
            }
            return {
              ...data,
              userItems: items,
              itemNum: items.length,
              face: status === 'NULL' ? '' :
                items[0]['url'], // 设置附件封面(默认为第一个附件)
              status: status
            };
          });
        }
      });
  }

  async openUserItemsModel(data: any) {
    // 打开审核项目对应的附件列表页model
    const modal = await this.modalCtrl.create({
      component: LoanUploadItemsComponent,
      componentProps: {
        title: data['name'],
        userItems: data['userItems'],
        bidId: data['bid_id'],
        bidAuditSubjectId: data['id']
      }
    });
    await modal.present();
    // 关闭model后，确认用户角色状态
    await modal.onDidDismiss();
  }

}
